package com.heer.gymnasium.module.store.views;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.base.BaseRefreshActivity;
import com.heer.gymnasium.module.coach.beans.CoachBean;
import com.heer.gymnasium.module.coach.beans.CoachResponseBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.adapters.HomeAdapter;
import com.heer.gymnasium.module.main.beans.CategoryBean;
import com.heer.gymnasium.module.store.beans.AreaBean;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.beans.StoreResponseBean;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.KeyBoardUtils;
import com.heer.gymnasium.util.StringUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.commonadapter.quick.Quick;
import com.zhihuiyun.library.utils.L;
import com.zhihuiyun.library.utils.SPUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by zy on 2018/1/18.
 */

public class StoreListActivity extends BaseRefreshActivity {

    private static final int RES_ID_ROOT_LAYOUT = R.layout.layout_store_list;
    private static final int RES_ID_REFRESH = R.id.refreshLayout;
    private static final int RES_ID_LIST = R.id.listview;
    private static final int RES_ID_SEARCH_TITLE = R.id.layout_title_search_bar_title_rl;
    private static final int RES_ID_SEARCH_RL = R.id.layout_title_search_bar_search_rl;

    private static final int RES_ID_AREA_SPINNER = R.id.layout_store_list_area_sp;
    private static final int RES_ID_TYPE_SPINNER = R.id.layout_store_list_type_sp;

    private static final int RES_ID_ITEM_SPINNER_LAYOUT = R.layout.item_dropdown;
    private static final int RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT = android.R.layout.simple_dropdown_item_1line;
    private static final int RES_ID_ITEM_SPINNER_TV = R.id.item_dropdown_type_tv;


    private static final int RES_ID_STORE_LAYOUT = R.layout.item_store;
    private static final int RES_ID_COACH_LAYOUT = R.layout.item_coach;


    private final static int RES_ID_SEARCH = R.id.layout_title_search_bar_search_iv;


    @BindView(RES_ID_SEARCH_BAR_ET)
    EditText searchBar;
    @BindView(RES_ID_LIST)
    ListView listView;
    @BindView(RES_ID_AREA_SPINNER)
    Spinner areaSpinner;
    @BindView(RES_ID_TYPE_SPINNER)
    Spinner typeSpinner;
    @BindView(RES_ID_SEARCH_RL)
    View searchView;
    @BindView(RES_ID_SEARCH_TITLE)
    View titleView;
    @BindView(RES_ID_SEARCH)
    ImageView searchImageView;

    private String DEFAULT_AREA;
    private String DEFAULT_SPORT_TYPE;

    //    当前页面类型 体育场 教练
    private int type;
    private QuickTypeAdapter<StoreBean> storeAdapter;
    private QuickTypeAdapter<CoachBean> coachAdapter;
    private ArrayAdapter<AreaBean> areaAdapter;
    private ArrayAdapter<CategoryBean> typeAdapter;

    private List<StoreBean> storeList;
    private List<CoachBean> coachList;
    private List<AreaBean> areaList;
    private List<CategoryBean> typeList;
    private StoreListActivity $this;
    private String areaCode = "", categoryId = "", keyword = "";
    private boolean isInit = true;

    @Override
    protected void init() {
        super.init();
        setContentView(RES_ID_ROOT_LAYOUT);
        $this = this;
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.hide();
        }
        setRefreshResId(RES_ID_REFRESH);
        DEFAULT_AREA = getResources().getString(R.string.store_area);
        DEFAULT_SPORT_TYPE = getResources().getString(R.string.gym_type);

        Quick.init(new Quick.QuickLoad() {
            @Override
            public void load(Context context, String url, ImageView view) {
                ImageUtil.loadUrl(context, url, R.drawable.banner, view);
            }
        });

        categoryId = getIntent().getStringExtra(EXTRA_ID);
        if (categoryId == null) {
            categoryId = "";
        }
    }

    @Override
    protected void initView() {
        super.initView();
        type = getIntent().getIntExtra(EXTRA_TYPE, -1);
        keyword = getIntent().getStringExtra(EXTRA_DATA);
        switch (type) {
            default:
                if (!TextUtils.isEmpty(keyword)) {
                    titleView.setVisibility(View.VISIBLE);
                    searchView.setVisibility(View.GONE);
                    type = TYPE_STORE;
                } else {
                    searchBar.setHint("找 运 动 场 馆");
                }
                break;
            case TYPE_COACH:
                searchBar.setHint("找 私 教");
                break;
        }
        areaList = new ArrayList<>();
        areaList.add(new AreaBean(DEFAULT_AREA));
        areaAdapter = new ArrayAdapter<AreaBean>(this, RES_ID_ITEM_SPINNER_LAYOUT, areaList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getArea());
                tv.setGravity(Gravity.CENTER);
                LinearLayout view = new LinearLayout($this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                convertView.setLayoutParams(layoutParams);
                view.addView(convertView);

                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView($this);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(10, 10, 10, 10);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getArea());
                return convertView;
            }
        };
        areaAdapter.setDropDownViewResource(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT);
        areaSpinner.setAdapter(areaAdapter);

        typeList = new ArrayList<>();
        CategoryBean defaultCategory = new CategoryBean();
        defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
        typeList.add(defaultCategory);
        typeAdapter = new ArrayAdapter<CategoryBean>(this, RES_ID_ITEM_SPINNER_LAYOUT, typeList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT, null);
                TextView tv = (TextView) convertView;
                tv.setText(getItem(position).getTitle());
                tv.setGravity(Gravity.CENTER);
                LinearLayout view = new LinearLayout($this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                convertView.setLayoutParams(layoutParams);
                view.addView(convertView);
                view.setOrientation(LinearLayout.VERTICAL);
                ImageView imageView = new ImageView($this);
                imageView.setBackgroundResource(R.color.bg_color);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
                view.addView(imageView);
                view.setPadding(10, 10, 10, 10);
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = getLayoutInflater().inflate(RES_ID_ITEM_SPINNER_LAYOUT, null);
                TextView tv = (TextView) convertView.findViewById(RES_ID_ITEM_SPINNER_TV);
                tv.setText(getItem(position).getTitle());
                return convertView;
            }
        };
        typeAdapter.setDropDownViewResource(RES_ID_ITEM_SPINNER_DROP_DOWN_LAYOUT);
        typeSpinner.setAdapter(typeAdapter);

        switch (type) {
            case TYPE_STORE:
                storeList = new ArrayList<>();
                storeAdapter = new QuickTypeAdapter<StoreBean>(this, storeList, RES_ID_STORE_LAYOUT) {
                    @Override
                    public void bindData4View(ViewHolder holder, StoreBean data, int type, int pos) {
                        HomeAdapter.bindStoreItem(context, holder, data, true);
                    }
                };
                listView.setAdapter(storeAdapter);
                break;
            case TYPE_COACH:
                coachList = new ArrayList<>();
                coachAdapter = new QuickTypeAdapter<CoachBean>(this, coachList, RES_ID_COACH_LAYOUT) {
                    @Override
                    public void bindData4View(ViewHolder holder, CoachBean data, int type, int pos) {
                        HomeAdapter.bindCoachItem(context, holder, data, pos);
                    }
                };
                listView.setAdapter(coachAdapter);
                break;
            default:
                ToastUtil.show(this, "参数异常");
                finish();
                break;
        }

        loadSelectorData();

        searchBar.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearch();
                }
                return false;
            }
        });
    }

    //两个spinner数据添加
    private void loadSelectorData() {
        getAreaList();
        getCategoryList();
    }

    @OnClick(RES_ID_SEARCH_BAR_BACK)
    public void back() {
        finish();
    }

    @OnClick(RES_ID_SEARCH)
    public void doSearch() {
        keyword = searchBar.getText().toString().replace("\n", "").trim();
        KeyBoardUtils.closeKeyboardWithoutFinish($this);
        loadData(false);
    }

    @Override
    protected void loadData(final boolean loadMore) {
        super.loadData(loadMore);
        switch (type) {
            case TYPE_COACH:
                getCoachList();
                break;
            case TYPE_STORE:
                getStadiumList();
                break;
        }
        setRefresh(false);
    }

    //    店铺
    private void getStadiumList() {
        L.e("pageNo " + pageNo);
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getStadiumList("", pageNo + "", SPUtils.get(this, SPUtils.SP_LA, IConstants.LA).toString(),
                SPUtils.get(this, SPUtils.SP_LO, IConstants.LO).toString(), categoryId, areaCode, keyword).enqueue(new BaseCallback<ApiResponse<StoreResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<StoreResponseBean>> call, Response<ApiResponse<StoreResponseBean>> response) {
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (response.body().getData().getData() == null || response.body().getData().getData().size() == 0) {
                    ToastUtil.show($this, "暂无信息");
                }
                if (pageNo == 1) {
                    storeList.clear();
                }
                if (total <= current * per_page) {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.TOP);
                }
                storeList.addAll(StoreBean.dataChange(response.body().getData().getData()));
                storeAdapter.notifyDataSetChanged();
            }
        });
    }

    //    私教
    private void getCoachList() {
        mAppHelper.apiService().getCoachList(null, null, null, pageNo + "", areaCode, categoryId, keyword).enqueue(new BaseCallback<ApiResponse<CoachResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<CoachResponseBean>> call, Response<ApiResponse<CoachResponseBean>> response) {
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (pageNo == 1) {
                    coachList.clear();
                }
                if (total <= current * per_page) {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.TOP);
                }
                coachList.addAll(CoachBean.dataChange(response.body().getData().getData()));
                coachAdapter.notifyDataSetChanged();
            }
        });
    }


    //获取区域列表
    private void getAreaList() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getAreaList(signHelper.GetParameter("key")).enqueue(new BaseCallback<ApiResponse<List<AreaBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<AreaBean>>> call, Response<ApiResponse<List<AreaBean>>> response) {
                areaList.clear();
                areaList.add(new AreaBean(DEFAULT_AREA));
                areaList.addAll(response.body().getData());
                areaAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call<ApiResponse<List<AreaBean>>> call, Throwable t) {
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    //获取区域列表
    private void getCategoryList() {
        mAppHelper.apiService().getCategoryList("").enqueue(new BaseCallback<ApiResponse<List<CategoryBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<CategoryBean>>> call, Response<ApiResponse<List<CategoryBean>>> response) {
                typeList.clear();
                CategoryBean defaultCategory = new CategoryBean();
                defaultCategory.setTitle(DEFAULT_SPORT_TYPE);
                typeList.add(defaultCategory);
                typeList.addAll(response.body().getData());
                typeAdapter.notifyDataSetChanged();
                for (int i = 0; i < typeList.size(); i++) {
                    if (TextUtils.isEmpty(categoryId)) {
                        typeSpinner.setSelection(0);
                        isInit = false;
                        break;
                    } else if (TextUtils.equals(categoryId, typeList.get(i).getId())) {
                        typeSpinner.setSelection(i);
                        isInit = false;
                        break;
                    }
                }

            }

            @Override
            public void onError(Call<ApiResponse<List<CategoryBean>>> call, Throwable t) {
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    public static final int TYPE_STORE = 0xabc;
    public static final int TYPE_COACH = 0xdef;

    public static void startActivity(Context context, int type, String category_id) {
        Intent mIntent = new Intent(context, StoreListActivity.class);
        mIntent.putExtra(EXTRA_TYPE, type);
        if (type == TYPE_STORE && !TextUtils.isEmpty(category_id)) {
            mIntent.putExtra(EXTRA_ID, category_id);
        }
        context.startActivity(mIntent);
    }

    public static void startActivity(Context context, int type) {
        startActivity(context, type, null);
    }

    //home界面找店铺跳转
    public static void startActivity(Context context, String keyword) {
        Intent mIntent = new Intent(context, StoreListActivity.class);
        mIntent.putExtra(EXTRA_DATA, keyword);
        context.startActivity(mIntent);
    }

    private void setRefresh(boolean flag) {
        if (layoutRefresh != null) {
            layoutRefresh.setRefreshing(flag);
        }
    }

    @OnItemSelected(RES_ID_AREA_SPINNER)
    public void onItemSelectedForArea(View view, int i) {
        pageNo = 1;
        layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTH);
        if (areaSpinner.getSelectedItemPosition() == 0) {
            areaCode = "";
        } else {
            areaCode = ((AreaBean) areaSpinner.getSelectedItem()).getAdcode();
        }
        loadData(false);
    }

    @OnItemSelected(RES_ID_TYPE_SPINNER)
    public void onItemSelectedForType(View view, int i) {
        pageNo = 1;
        layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTH);
        if (!isInit) {
            if (typeSpinner.getSelectedItemPosition() == 0) {
                categoryId = "";
            } else {
                categoryId = ((CategoryBean) typeSpinner.getSelectedItem()).getId();
            }
        }
        loadData(false);
    }
}
